var mysql  =require('mysql');
var dbConfig = require('../db/dbConfig');
var userSQL = require('../db/usersql');
var express = require('express');
var router = express.Router();


var pool = mysql.createPool(dbConfig.mysql);
//响应一个json 数据
var responseJSON = function(res,ret){
	if(typeof ret ==='undifind'){
		res.json({
			code:'-200',
			msg:'操作失败'
		})
	}else{
		res.json(ret);
	}
}
/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});



/*注册接口*/
router.get('/register',function(req,res,next){

	pool.getConnection(function(err,connection){
		//获取前端传过来的数据
		var param = req.query||req.paramsl;//接收前端数据
			console.log(param)
		var data = {};
		var _res = res;
		var userName = param.userName;
		var passWord = param.passWord;
		if(!userName){
			data.result = {
				code:2,
				msg:'用户名不能为空'
			}
			setTimeout(function(){
				responseJSON(_res,data);
			},300)
			data.isreg = false;
			return;
		}
		console.log(param)
		connection.query(userSQL.queryAll,function(err,res){
			var isHas = false;//判断是否有注册过
			if(res){  //获取用户列表
				for(var i = 0;i<res.length;i++){
					if(userName==res[i].userName&&passWord==res[i].passWord){
						isHas = true   //证明已经注册过
					}
				}
			}
			data.isreg = !isHas;
			if(isHas){  //用户存在
				data.result = {
					code:1,
					msg:'用户存在'
				}
			}else{//如果用户不存在
				 connection.query(userSQL.insert,[param.userName,param.passWord],function(err,res){
				 	if(res){
				 		data.result = {
				 			code:200,
				 			msg:'注册成功'
				 		}
				 	}else{
				 		data.result = {
				 			code:-1,
				 			msg:'注册失败'
				 		}
				 	}
				 })
			}
			if(err) data.err = err;
			//一json的形式返回给前台
			setTimeout(function(){
				responseJSON(_res,data)
			},300)
			//释放链接
			connection.release();
		})
	})
})

//登录借口
router.get('/login',function(req,res,next){
	var _res = res
	var data = {};
	 pool.getConnection(function(err,connection){
	 	var param = req.query||req.paramsl  //获取前端数据
	 	var userName = param.userName;  
	 	var passWord = param.passWord;
	 	console.log(userName);
	 	var isreg = false;
	 	connection.query(userSQL.queryAll,function(err,res){
	 		if(res){
	 			console.log(res);
	 			for(var i = 0;i<res.length;i++){
	 				if(res[i].userName==userName&&res[i].passWord==passWord){//假如已经注册过
	 					isreg = true;
	 				}
	 			}
	 		}
	 		data.isreg = isreg
	 		if(isreg){//如果登录成功
	 			data.result = {
	 				code:200,
	 				msg:'登录成功'
	 			}
	 		}else{
	 			data.result = {
	 				code:-1,
	 				msg:'登录失败'
	 			}
	 		}
	 		
	 			if(err) data.err = err;
			//一json的形式返回给前台
			setTimeout(function(){
				responseJSON(_res,data)
			},300)
			//释放链接
			connection.release();
	 	})
	 })
})

module.exports = router;
  